package com.cqan.controller;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.ModelAndView;

import com.cqan.account.entity.User;
import com.cqan.entity.pk.IdEntity;
import com.cqan.exception.AppException;
import com.cqan.service.EntityService;

public abstract class BaseController<Entity extends IdEntity, PK extends Serializable,BaseService extends EntityService<Entity,PK>> {

	protected BaseService entityService;

	protected Class<Entity> entityClass;
	
	protected Logger logger = Logger.getLogger("ds.debug");

	protected User getUserDetails() {
		Object obj = SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
		if (obj instanceof User) {
			return (User) obj;
		}
		return null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Entity getRequestEntity(HttpServletRequest req)throws AppException {
		try {
			this.entityClass = ((Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
			if (entityClass != null) {
				Entity entity = entityClass.newInstance();
				Field[] fields = entityClass.getDeclaredFields();
				for (Field field : fields) {
					 field.setAccessible(true);
					 field.set(field.getName(), req.getParameter(field.getName()));
				}
				return entity;
			}
		} catch (Exception e) {
			logger.debug(e.getLocalizedMessage());
			throw new AppException("base.assignment");
		} 
		return null;
	}
	
	public abstract void setEntityService(BaseService entityService);
	
	
}
